package org.feng.start.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * mybatis-plus配置
 *
 * @author feng
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    @Primary
    @SneakyThrows
    public SqlSessionFactory sqlSessionFactory(@Autowired DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        MybatisConfiguration configuration = new MybatisConfiguration();
        sqlSessionFactoryBean.setConfiguration(configuration);
        // 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
        configuration.setMapUnderscoreToCamelCase(true);
        // 如果查询结果中包含空值的列，则 MyBatis 在映射的时候，不会映射这个字段
        configuration.setCallSettersOnNulls(true);
        // 日志
        configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        // 实体包
        sqlSessionFactoryBean.setTypeAliasesPackage("org.feng.start.entity");
        // mapper.xml位置
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resourceResolver.getResources("classpath*:mapper/**Mapper.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);

        // 设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);

        // 设置GlobalConfig
        GlobalConfigUtils.setGlobalConfig(configuration, globalConfig());

        // 返回SqlSessionFactory
        return sqlSessionFactoryBean.getObject();
    }

    private GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setIdType(IdType.AUTO);
        globalConfig.setDbConfig(dbConfig);

        return globalConfig;
    }
}
